package com.zsw.service.impl;

import com.zsw.dao.StorageDao;
import com.zsw.exception.BusinessException;
import com.zsw.entity.Storage;
import com.zsw.exception.UserErrorEnum;
import com.zsw.service.StorageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author zhangsw
 */
@Service
@Transactional(rollbackFor = {Exception.class})
public class StorageServiceImpl implements StorageService {

    @Resource
    private StorageDao storageDao;

    @Override
    public boolean deduct(int commodityCode, int count) {
        if(count <= 0){
            throw new BusinessException("参数错误");
        }
        Storage storage = storageDao.selectStorageByCommodityCode(commodityCode);
        if(storage!=null) {
            if (count > storage.getCount()) {
//                throw new BusinessException(UserErrorEnum.USER_NOT_EXIST_ERROR);
                throw new RuntimeException("库存扣减失败，库存不足");
            }
            storage.setCount(storage.getCount() - count);
            int result=storageDao.updateStorage(storage);
            return result>0;
        }
        return false;
    }
}
